package cn.itcast.rabbitmq;

import cn.itcast.util.TextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;

/**
 * @Author lyy
 * @Description TODO
 * @PACKAGE_NAME: cn.itcast.rabbitmq
 * @ClassName RabbitmqListener
 * @Date 2020/7/2 9:03
 * @DAY_NAME_FULL: 星期四
 * @Version 1.0
 **/
public class RabbitmqListener {

    protected Logger logger= LoggerFactory.getLogger(this.getClass());

    protected String messageToString(Message message){
        String body = null;
        try {
            //消息转成String
            body = new String(message.getBody(),"utf8");
            logger.info("RabbitMQ队列=>" + message.getMessageProperties().getConsumerQueue() + "接受到的消息--->" + body + "\t Message--->" +message);
        }catch (Exception e){
            logger.info("RabbitMQ队列=>" + message.getMessageProperties().getConsumerQueue() + "接受到的消息--->" + body,e);
        }
        return body;
    }

    protected JSONObject messageToJSONObject(Message message){
        String text = this.messageToString(message);
        if(TextUtils.isEmpty(text)) return null;
        try {
            return JSON.parseObject(text);
        }catch (Exception e){
            logger.error(message.getMessageProperties().getConsumerQueue() + "消息转JSON发生了异常" ,e);
            return null;
        }
    }
}
